<template>
  <div class="main_box" style="padding:10px">
    <div class="add_wrap">
      <div class="tit">
        <h2>{{ dataForm.waiterId ? '编辑服务员' : '新增服务员' }}</h2>
        <el-button type="success" plain size="small" icon="fa fa-mail-forward" @click="returnList">返回</el-button>
      </div>
      <el-form :model="dataForm" ref="dataForm" label-width="200px" :rules="roleRules">
        <el-row>
          <el-form-item prop="waiterType" label="类型">
            <el-select placeholder="请选择服务员类型" v-model="dataForm.waiterType" @change="handleWaiterTypeChange">
              <el-option v-for="item in waiterTypeList" :key="item.value" :value="item.value" :label="item.label">

              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="jobType" label="工作类型" v-model="dataForm.jobType" v-if="dataForm.waiterType==2">
            <el-select placeholder="请选择工作类型" v-model="dataForm.jobType">
              <el-option v-for="item in jobTypeList" :key="item.id" :value="item.id" :label="item.name">

              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="businessId" label="商户">
            <el-select placeholder="请选择商户" v-model="dataForm.businessId" clearable filterable
                       @change="handleBusinessChange()">
              <el-option v-for="item in businessList" :key="item.id" :value="item.id" :label="item.name">

              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="departIds" label="部门" v-show="dataForm.waiterType === 1">
            <el-cascader v-model="dataForm.departIds"
                         :props="{ label: 'departName', value: 'departId', checkStrictly: true }"
                         :options="departList">

            </el-cascader>
          </el-form-item>

          <el-form-item prop="userName" label="账号" v-if="dataForm.waiterId">
            <el-input type="text" v-model="dataForm.userName" :disabled="true"></el-input>
          </el-form-item>
          <el-form-item prop="nickName" label="昵称" v-if="dataForm.waiterId">
            <el-input type="text" v-model="dataForm.nickName"></el-input>
          </el-form-item>

          <el-form-item prop="fullName" label="姓名">
            <el-input type="text" v-model="dataForm.fullName"></el-input>
          </el-form-item>
          <el-form-item prop="sex" label="性别">
            <el-radio-group v-model="dataForm.sex">
              <el-radio :label="1">男</el-radio>
              <el-radio :label="2">女</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item prop="phone" label="绑定手机号">
            <el-input :read-only="$route.query.id" type="text" v-model="dataForm.phone"></el-input>
          </el-form-item>

          <!-- <el-form-item prop="sysDepartId" label="公司" v-show="dataForm.waiterType == 2">
            <el-cascader v-model="dataForm.sysDepartId" :options="sysDepartList"
              :props="{ value: 'departId', label: 'departName', children: 'childrens', checkStrictly: true, emitPath: false }"
              clearable filterable>
            </el-cascader>
          </el-form-item> -->
          <el-form-item prop="takeOrdersWay" label="接单方式" v-show="takeOrdersWay==2">
            <el-radio-group v-model="dataForm.takeOrdersWay">
              <el-radio :label="1">手动接单</el-radio>
              <el-radio :label="2">自动接单</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item prop="remark" label="备注">
            <el-input type="textarea" v-model="dataForm.remark"></el-input>
          </el-form-item>
          <el-form-item prop="scheduleAuthority" label="排班权限">
            <el-radio-group v-model="dataForm.scheduleAuthority">
              <el-radio :label="0">无</el-radio>
              <el-radio :label="1">有</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="下班方式" v-show="workOffWay==1">
            <el-radio-group v-model="dataForm.workOffWay" >
              <el-radio :label="1">手动下班</el-radio>
              <el-radio :label="2">自动下班</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="个人信息管理权限" v-show="dataForm.waiterType==1&&businessDetailType==2">
            <el-radio-group v-model="dataForm.personPower">
              <el-radio :label="0">无</el-radio>
              <el-radio :label="1">有</el-radio>
            </el-radio-group>
          </el-form-item>


          <el-form-item style="width: 1000px;" v-if="!dataForm.waiterId">
            <span style="color: red;">说明：新增时，登录账号和昵称会自动生成，生成规则：登录账号=手机号，昵称=商户昵称+“-”+姓名</span>
          </el-form-item>
        </el-row>
        <template v-if="dataForm.businessId&&(dataForm.waiterType===2||businessDetailType==2)&&dataForm.personPower==1">
          <div class="tit" >
            <h2>商户管理范围</h2>
          </div>
          <el-row>
            <el-table ref="businessVillagesTableRef" :data="businessVillages" style="width:fit-content"
              @row-click="handleSelectionChange($event,1)"
              @selection-change="handleSelectionChange($event,2)">
              <el-table-column label="地区" prop="address" width="370" align="center">

              </el-table-column>
              <el-table-column label="小区" prop="villageName" align="center" width="300">

              </el-table-column>
              <el-table-column v-if="businessDetailType==2&&dataForm.waiterType===1" type="selection" width="100" align="center"></el-table-column>
            </el-table>
          </el-row>
        </template>
        <template v-if="dataForm.waiterType === 2">
          <div class="tit">
            <h2>管理范围</h2>
            <el-button icon="el-icon-plus" type="success" plain size="medium" circle @click="addBtnRegion">
            </el-button>
          </div>
          <el-row>
            <el-table :data="dataForm.waiterVillages" style="width:max-content;">
              <el-table-column label="操作" width="70" align="center">
                <template slot-scope="scope">
                  <el-button icon="el-icon-minus" type="danger" plain size="medium" circle
                            @click="subBtnRegion(scope.$index)">
                  </el-button>
                </template>
              </el-table-column>

              <el-table-column label="地区" width="320" align="center">
                <template slot-scope="scope">
                  <Region style="width:300px" ref="region" :streetValues="scope.row.streetIds"
                          @regionChange="handleItemChange" :isChangeOnSelect="true" :index="scope.$index"></Region>
                </template>
              </el-table-column>
              <el-table-column label="小区" width="280" align="center">
                <template slot-scope="scope">
                  <el-select v-model="scope.row.villageId" style="width: 240px;"
                            @focus="handleVillageFocus(scope.row.streetIds, scope.$index)"
                            @change="handleVillageChange(scope.row, scope.$index)" clearable>
                    <el-option v-for=" item  in  scope.row.villageList " :value="item.id" :label="item.name"
                              :key="item.id">

                    </el-option>
                  </el-select>
                </template>
              </el-table-column>
            </el-table>
          </el-row>
        </template>
        <el-row>
          <el-form-item>
            <el-button plain type="primary" @click="sureClick">保 存</el-button>
            <el-button plain @click="returnList">取 消</el-button>
          </el-form-item>
        </el-row>
      </el-form>
    </div>
  </div>
</template>

<script>
import * as message from "@/constants/message";
import WaiterApi from '@/api/business/waiter';
import BusinessApi from "@/api/business/business";
import BusinessDepartApi from "@/api/business/depart"
import {getStorage} from '@/utils/auth';
import {USER_INFO} from "@/constants/storeName";
import Region from "@/components/Region";
import VillageApi from "@/api/address/village";
import AdminVillageApi from "@/api/common/adminVillage"
import DepartApi from "../../api/system/depart";

export default {
  data() {
    return {
      userInfo: "",
      waiterVillages: [],
      takeOrdersWay:1,// 1表示商户仅允许服务员手动接单，2表示服务员可自己选择自动接单
      workOffWay:2, // 1表示商户允许服务员自己选择自动下班，2表示仅手动打卡下班
      businessDetailType:"",// 1表示普通商户 2表示社区商户
      dataForm: {
        waiterId: "",
        userName: "",
        waiterType: "",
        departIds: [],
        // sysDepartId:"",
        fullName: "",
        sex: 1,
        // userCode: "",
        businessId: "",
        nickName: "",
        phone: "",
        takeOrdersWay:1,//1 手动接单（默认） 2自动接单
        workOffWay:1,// 1 手动下班(默认) 2//自动下班
        jobType:0, // 0 普通 1 时段产品专员
        scheduleAuthority:0, // 0表示无权限 1表示有权限
        personPower:1,// 1表示有 0表示无
        remark: "",
        waiterVillages: [
          {
            provinceId: "",
            provinceName: "",
            cityId: "",
            cityName: "",
            areaId: "",
            areaName: "",
            streetId: '',
            streetName: "",
            villageId: "",
            villageName: "",
            levels: "",
            streetIds: [],//地区数组id,提交的时候要删掉
            villageList: [],//小区列表,提交的时候要删掉
          }
        ],
      },
      businessList: [],
      businessVillages: [],
      waiterTypeList: [
        {value: 1, label: "专属服务员"},
        {value: 2, label: "公共服务员"}
      ],
      jobTypeList:[
        {id:0,name:"普通"},
        {id:1,name:"时段产品专员"}
      ],
      departList: [],
      loadingIns: false,
      roleRules: {

        /*nickName: [
          {required: true, message: "请输人昵称", trigger: "blur"}
        ],
        userName: [
          {required: true, message: "请输入账号", trigger: "change"}
        ],*/
        waiterType: [
          {required: true, message: "请选择类型", trigger: "change"}
        ],
        businessId: [
          {required: true, message: "请选择商户", trigger: "change"}
        ],
        fullName: [
          {required: true, message: "请输人姓名", trigger: "blur"}
        ],
        sex: [
          {required: true, message: "请选择性别", trigger: "change"}
        ],
        phone: [
          {required: true, message: "请输入手机号", trigger: "blur"},
          {pattern: /^1(3|4|5|6|7|8|9)\d{9}$/, message: "手机号格式错误", trigger: "blur"}
        ],
        roleRules:[],
      },
      selectedBusinessVillages:[],
      // sysDepartList:[],
    }
  },
  components: {
    Region
  },
  watch: {
    // 'dataForm.businessId': {
    //   handler(val) {
    //     if (val) {
    //       this.getDepartList()
    //     } else {
    //       this.dataForm.departIds = [];
    //       this.departList = [];
    //     }
    //   },
    //   immediate: true
    // },
    'dataForm.waiterType':{
      async handler(val){
        const {roleRules} = this
        if(val==1){
          Reflect.deleteProperty(roleRules,'jobType')
        }else{
          this.$set(roleRules,'jobType',[{required: true, message: "请选择工作类型", trigger: "change"}])
        }
        await this.$nextTick()
        this.$refs.dataForm.clearValidate()
      },
    },
  },
  mounted() {
    this.init()
  },
  methods: {
    init() {
      // 获取用户的信息
      this.userInfo = getStorage(USER_INFO)
      // 当是进来的是商户的时候因为不能选择商户这个字段，所以校验规则需要做改变去掉商户校验
      // if (this.userInfo.userRole == 3) {
      //   this.$delete(this.roleRulesAdd, "businessId")
      //   this.$delete(this.roleRulesEdit, "businessId")
      //   this.$nextTick(() => {
      //     // 调用nextTick生命周期函数避免
      //     this.$refs['dataForm'].resetFields();
      //   })
      // }

      this.getBusinessList()
      // this.getSysDepartList()
      if (this.$route.query.id) {
        this.dataForm.waiterId = this.$route.query.id
        this.getData()
      }
    },
    keydown(e) {
      if (e.keyCode == 32) {
        e.returnValue = false;
      }
    },
    getDepartList() {
      BusinessDepartApi.listMangerTree({businessId: this.dataForm.businessId}).then(res => {
        this.setDisabled(res.data||[])
        this.departList = res.data||[]
      })
    },
    // 设置部门中哪些不可选
    setDisabled(list) {
      list.forEach(item => {
        if (!item.power) {
          item.disabled = true
        }
        if (item.children) {
          this.setDisabled(item.children)
        }

      })
    },
    handleWaiterTypeChange() {
        this.dataForm.businessId = ""
        this.dataForm.takeOrdersWay = 1
        this.dataForm.workOffWay = 1
        this.dataForm.jobType = this.dataForm.waiterType==2?0:""
    },
    addBtnRegion() {
      this.dataForm.waiterVillages.push({
        provinceId: "",
        provinceName: "",
        cityId: "",
        cityName: "",
        areaId: "",
        areaName: "",
        streetId: '',
        streetName: "",
        villageId: "",
        villageName: "",
        levels: "",
        houseId: "",
        streetIds: [],
        villageList: [],
        houseList: [],
      })
    },
    subBtnRegion(index) {
      this.dataForm.waiterVillages.splice(index, 1)
    },
    handleItemChange(val) {
      if (val.index!==undefined) {
        // 当是列表里面的数据的时候，传了索引过去，所以接收索引
        let region = this.dataForm.waiterVillages[val.index]
        region.villageList = [] //清空小区列表
        region.villageId = "" //清空对应的小区id
        region.villageName = ""//清空小区对应的名字
        region.houseId = "" //清空设备地址
        region.houseList = [] //清空设备地址列表
        region.levels = ""
        region.provinceId = val.provinceId;
        region.provinceName = val.provinceName;
        region.cityId = val.cityId;
        region.cityName = val.cityName;
        region.areaId = val.areaId;
        region.areaName = val.areaName;
        region.streetId = val.streetId
        region.streetName = val.streetName
        region.levels = val.levels
        if (val.provinceId) {
          region.streetIds = [
            val.provinceId,
            val.cityId,
            val.areaId,
            val.streetId,
          ];
        } else {
          region.streetIds = []
        }
      } else {
        // 没有传索引过去
        this.dataForm.provinceId = val.provinceId;
        this.dataForm.provinceName = val.provinceName;
        this.dataForm.cityId = val.cityId;
        this.dataForm.cityName = val.cityName;
        this.dataForm.areaId = val.areaId;
        this.dataForm.areaName = val.areaName;
        this.dataForm.streetId = val.streetId;
        this.dataForm.streetName = val.streetName;
        this.dataForm.streetIds = [val.provinceId, val.cityId, val.areaId, val.streetId];
      }
    },
    handleVillageFocus(streetIds, index) {
      // 点击小区的时候调用接口
      // let levels = this.dataForm.waiterVillages[index].levels
      // if (levels == 3 || levels == 4 || levels == 5) {
      streetIds = streetIds.filter(item => typeof item == "number") //有名字的话就要过滤掉
      let param = {
        provinceId: streetIds[0],
        cityId: streetIds[1],
        areaId: streetIds[2],
        streetId: streetIds[3],
        name: "",
      }
      VillageApi.villageList(param).then(res => {
        // this.$set(this.dataForm.businessVillages[index],"villageList",res.data)
        this.dataForm.waiterVillages[index].villageList = res.data
      })
      // }
    },
    handleVillageChange(row, index) {
      // 需要拿到小区的名字放在数组里一起传给后台
      let value = this.dataForm.waiterVillages[index]
      value.houseId = ""
      value.houseList = []
      if (row.villageId) {
        let obj = value.villageList.find(item => item.id == row.villageId)
        value.villageName = obj.name
      } else {
        value.villageName = ""
      }
    },
    /**
     * init表示初始化编辑的时候
     */
    async handleBusinessChange(init=false) {
      const {dataForm: {businessId, waiterType,waiterVillages}} = this

      if(!init){
        console.log("走这里")
        this.dataForm.departIds = []
        this.departList = []
      }
      if(businessId){
          this.getDepartList()
          const target = this.businessList.find(item=>item.id == businessId)
          this.takeOrdersWay = target.takeOrdersWay
          this.workOffWay = target.workOffWay
          if(this.takeOrdersWay==1)this.dataForm.takeOrdersWay = 1
          if(this.workOffWay==2)this.dataForm.workOffWay = 1
          this.businessDetailType = target.detailType
          if (waiterType == 2||waiterType==1&&target.detailType) {
            // 如果是公共服务员
            let res = await AdminVillageApi.listVillage({businessId})
            res = res.data || []
            res.forEach(item => {
              item.address = (item.provinceName || "") + (item.cityName || "") + (item.areaName || "") + (item.streetName || "")
            })
            this.businessVillages = res
          }
          if(init){
            if(target.detailType==2&waiterType==1){
              let arr = []
              // 社区商户，进来编辑的时候,如果是社区商户还要选中那些管理范围
              this.businessVillages.forEach(item=>{
                waiterVillages.find(item2=>this.$Utils.isAddressSame(item2,item))&&arr.push(item)
              })
              if(arr.length){
                await this.$nextTick()
                arr.forEach(item=>this.$refs.businessVillagesTableRef.toggleRowSelection(item))
              }
            }
          }
      }else{
        this.takeOrdersWay = 1
        this.workOffWay = 2
        this.dataForm.takeOrdersWay = 1
        this.dataForm.workOffWay = 1
        this.businessDetailType = 1
        this.dataForm.personPower = 1
      }
    },
    handleSelectionChange(val,type){
      if(this.dataForm.waiterType==2) return
      if(type==1){
        this.$refs.businessVillagesTableRef.toggleRowSelection(val)
      }else{
        this.dataForm.waiterVillages = val.map(item=>({
          provinceId: item.provinceId,
          provinceName: item.provinceName,
          cityId: item.cityId,
          cityName: item.cityName,
          areaId: item.areaId,
          areaName: item.areaName,
          streetId: item.streetId,
          streetName: item.streetName,
          villageId: item.villageId,
          villageName: item.villageName,
        }))
      }
    },
    async getData() {
      const {data} = await WaiterApi.getWaiterInfo({id: this.dataForm.waiterId})
      data.waiterVillages = data.waiterVillages.map(item => {
        let obj = {
          provinceId: item.provinceId,
          provinceName: item.provinceName,
          cityId: item.cityId,
          cityName: item.cityName,
          areaId: item.areaId,
          areaName: item.areaName,
          streetId: item.streetId,
          streetName: item.streetName,
          villageId: item.villageId,
          villageName: item.villageName,

        }
        obj.streetIds = Object.values(obj)
        obj.levels = item.levels
        if (item.villageId && item.villageName) {
          obj.villageList = [{id: item.villageId, name: item.villageName}]
        } else {
          obj.villageList = []
        }
        return obj
      })

      const departIds = []
      data.departId&&departIds.push(data.departId)
      data.firstDepartId&&departIds.push(data.firstDepartId)
      data.secondDepartId&&departIds.push(data.secondDepartId)
      data.thirdDepartId&&departIds.push(data.thirdDepartId)
      data.departIds = departIds

      this.$Utils.bindingBean(this.dataForm,data)


      this.handleBusinessChange(true)
      // 这里必须要使用nextTick函数否则Region组件不会渲染出来，且下面必须使用$set。
      // this.$nextTick(() => {
      //   if (this.dataForm.waiterVillages.length > 0) {
      //     this.dataForm.waiterVillages.forEach((item, index) => {
      //       this.$set(item, "streetIds", [
      //         item.provinceId,
      //         item.provinceName,
      //         item.cityId,
      //         item.cityName,
      //         item.areaId,
      //         item.areaName,
      //         item.streetId,
      //         item.streetName
      //       ])
      //     })
      //   }
      // })


    },
    // 获取商户列表
    getBusinessList() {
      BusinessApi.listIdNameVo().then(res => {
        this.businessList = res.data
      })
    },
    async sureClick() {
      await this.$refs.dataForm.validate()
      let {waiterType,waiterId,waiterVillages} = this.dataForm
      // 对经营区域表进行处理，先去掉空的行，再判断是否至少加了一行数据(必须加)，最后过滤筛选出需要提交的数据

      if (waiterType == 2) {
        this.dataForm.waiterVillages = waiterVillages = waiterVillages.filter(item => item.provinceId)
        if (waiterVillages.filter(item => item.provinceId).length == 0) {
          this.$message.error("请至少选择一个服务范围")
          return
        }
        // 这里用一个新的数据接收,要过滤掉里面的数组
        this.waiterVillages = waiterVillages.map(item => {
          return {
            provinceId: item.provinceId,
            provinceName: item.provinceName,
            cityId: item.cityId,
            cityName: item.cityName,
            areaId: item.areaId,
            areaName: item.areaName,
            streetId: item.streetId,
            streetName: item.streetName,
            villageId: item.villageId,
            villageName: item.villageName,//
            levels: item.villageId ? 5 : item.levels,  //需要在这里判断villageId如果存在levels就代表第五层小区
          }
        })
      }
      await this.$confirm(message.MSG_CONFIRM_SAVE_ALTER, message.TITLE_PROMPT, {})
      waiterId?this.editData():this.addData()
    },
    addData() {
      let param = {
        userName: this.dataForm.userName,
        fullName: this.dataForm.fullName,
        nickName: this.dataForm.nickName,
        sex: this.dataForm.sex,
        waiterType: this.dataForm.waiterType,
        businessId: this.dataForm.businessId,
        phone: this.dataForm.phone,
        takeOrdersWay:this.dataForm.takeOrdersWay,
        workOffWay:this.dataForm.workOffWay,
        remark: this.dataForm.remark,
        jobType:this.dataForm.jobType,
        scheduleAuthority:this.dataForm.scheduleAuthority,
      };
      if (param.waiterType == 1) {

        if(this.businessDetailType==2&&this.dataForm.personPower==1){
          param.waiterVillages = this.waiterVillages
        }
        param.personPower = this.dataForm.personPower
        param.departId = this.dataForm.departIds[0] || ""
        param.firstDepartId = this.dataForm.departIds[1] || ""
        param.secondDepartId = this.dataForm.departIds[2] || ""
        param.thirdDepartIds = this.dataForm.departIds[3] || ""
      } else {
        // param.sysDepartId = this.dataForm.sysDepartId||""
        param.waiterVillages =  this.dataForm.waiterVillages
      }
      WaiterApi.addWaiter(param).then(res => {
        this.$Utils.notifySuccess()
        this.returnList();
      })
    },
    editData() {
      let param = {
        waiterId: this.dataForm.waiterId,
        userName: this.dataForm.userName,
        waiterType: this.dataForm.waiterType,
        fullName: this.dataForm.fullName,
        nickName: this.dataForm.nickName,
        sex: this.dataForm.sex,
        // userCode: this.dataForm.userCode,
        businessId: this.dataForm.businessId,
        phone: this.dataForm.phone,
        takeOrdersWay:this.dataForm.takeOrdersWay,
        workOffWay:this.dataForm.workOffWay,
        remark: this.dataForm.remark,
        jobType:this.dataForm.jobType,
        scheduleAuthority:this.dataForm.scheduleAuthority,
      };
      if (param.waiterType == 1) {
        if(this.businessDetailType==2&&this.dataForm.personPower==1){
          param.waiterVillages = this.dataForm.waiterVillages
        }
        param.personPower = this.dataForm.personPower
        param.departId = this.dataForm.departIds[0] || ""
        param.firstDepartId = this.dataForm.departIds[1] || ""
        param.secondDepartId = this.dataForm.departIds[2] || ""
        param.thirdDepartIds = this.dataForm.departIds[3] || ""
      } else {
        // param.sysDepartId = this.dataForm.sysDepartId||""
        param.waiterVillages = this.waiterVillages
      }
      WaiterApi.editWaiter(param)
        .then(data => {
          this.$Utils.notifySuccess()
          this.returnList();
        })
    },
    returnList() {
      this.$store.dispatch('delView', this.$route);
      this.$router.back();
    }
  },

}
</script>
<style lang="scss" scoped>
@import "@/assets/css/views/add.scss";
</style>
